<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="nickname">
        <el-input v-model="queryParams.nickname" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="手环开放状态" prop="huaweiStatus">
        <el-select v-model="queryParams.huaweiStatus" placeholder="手环绑定状态" clearable style="width: 240px">
          <el-option v-for="dict in sys_huawei_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="手环绑定状态" prop="bindFlag">
        <el-select v-model="queryParams.bindFlag" placeholder="手环绑定状态" clearable style="width: 240px">
          <el-option v-for="dict in sys_bind_flag" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="用户状态" clearable style="width: 240px">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"-->
<!--          v-hasPermi="['mobile:patient:add']">新增</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mobile:patient:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" height="800" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="false" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column fixed label="姓名" align="center" prop="nickname" />
      <el-table-column label="头像" align="center" prop="avatar">
        <template #default="scope">
          <img :src="scope.row.avatar" min-width="70" height="70" />
        </template>
      </el-table-column>
      <el-table-column label="手术时间" align="center" prop="operationTime">
        <template #default="scope">
          {{scope.row.operationTime || "----"}}
        </template>
      </el-table-column>
      <el-table-column label="体脂率" align="center" prop="fatPercent" />
      <el-table-column label="累计打卡天数" align="center" prop="checkinCount" />
      <el-table-column label="坚持打卡天数" align="center" prop="goonCount" />
      <el-table-column label="手环sn" align="center" prop="sn" />

      <el-table-column label="手环绑定时间" align="center" prop="bindTime">
        <template #default="scope">
          {{scope.row.bindTime || "----"}}
        </template>
      </el-table-column>

      <el-table-column label="手环开放状态" align="center" prop="huaweiStatus">
        <template #default="scope">
          <dict-tag :options="sys_huawei_status" :value="scope.row.huaweiStatus" />
        </template>
      </el-table-column>

      <el-table-column label="手环绑定状态" align="center" prop="bindFlag">
        <template #default="scope">
          <dict-tag :options="sys_bind_flag" :value="scope.row.bindFlag" />
        </template>
      </el-table-column>
      <el-table-column label="帐号状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mobile:patient:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mobile:patient:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleMedicalAdd(scope.row)"
            v-hasPermi="['mobile:medicalrecord:add']">新增病历</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleUserQuestionaireList(scope.row)"
            v-hasPermi="['mobile:userquestionaire:list']">调查问卷</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" v-model="open" :width="dialogWidth" append-to-body>
      <el-form ref="userForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="openid" prop="openid">
          <el-input v-model="form.openid" placeholder="请输入用户openid" readonly="true" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入用户手机号" readonly="true"/>
        </el-form-item>
        <el-form-item label="姓名" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入姓名" readonly="true"/>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input type="hidden" v-model="form.avatar" placeholder="请输入头像" readonly="true"/>
          <!-- <ImageUpload :modelValue="form.avatar ? [{name:'xx',url:form.avatar}]: []" :limit="1" @update="changeUpload" apiUrl="/common/uploadImg" /> -->
          <ImageUpload v-model="form.avatar" :data={type:1} :limit="1" :isShowTip="false" :dis="true" apiUrl="/common/uploadImg" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio v-for="dict in sys_patient_sex" :key=dict.value :label=dict.value>{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker v-model="form.birthday" type="date" :style="{width: '100%'}" placeholder="请选择日期" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所在地区" prop="area">
          <el-input v-model="form.area" placeholder="请输入所在地区" />
        </el-form-item>
        <el-form-item label="地区码" prop="areaCode">
          <el-input v-model="form.areaCode" placeholder="请输入地区码" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="累计打卡天数" prop="checkinCount">
          <el-input v-model="form.checkinCount" placeholder="请输入累计打卡天数" />
        </el-form-item>
        <el-form-item label="坚持打卡天数" prop="goonCount">
          <el-input v-model="form.goonCount" placeholder="请输入坚持打卡天数" />
        </el-form-item>

        <el-form-item label="手环开放状态" prop="huaweiStatus">
          <el-radio-group v-model="form.huaweiStatus">
            <el-radio v-for="dict in sys_huawei_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手环绑定状态" prop="bindFlag">
          <el-radio-group v-model="form.bindFlag">
            <el-radio v-for="dict in sys_bind_flag" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="华为授权状态" prop="huaweiAuthorizeComplete">
          <el-radio-group v-model="form.huaweiAuthorizeComplete">
            <el-radio v-for="dict in sys_huawei_authorize_status" :key=dict.value :label=dict.value>{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="用户状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Patient">
import { listUser, getUser, delUser, addUser, updateUser } from "@/api/mobile/patient";

const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_bind_flag, sys_normal_disable, sys_patient_sex, sys_huawei_authorize_status, sys_huawei_status } = proxy.useDict("sys_bind_flag", "sys_normal_disable", "sys_patient_sex", "sys_huawei_authorize_status", "sys_huawei_status");


const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const dialogWidth = ref("0")

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    phone: null,
    nickname: null,
    bindFlag: null,
    status: null,
  },
  // 表单参数
  form: {},
  // 表单校验
  rules: {}
})

const { queryParams, form, rules } = toRefs(data);


/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then(response => {
    userList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    openid: null,
    phone: null,
    nickname: null,
    avatar: null,
    sex: null,
    birthday: null,
    areaCode: null,
    area: null,
    address: null,
    checkinCount: null,
    goonCount: null,
    huaweiStatus: null,
    bindFlag: null,
    huaweiAuthorizeComplete: null,
    status: "0"
  };
  proxy.resetForm("form");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}


function handleMedicalAdd(row) {
  const id = row.id
  router.push("/mobile/medical-record/add/" + id);
}

function handleUserQuestionaireList(row) {
  const id = row.id
  router.push("/mobile/userquestionaire/list/" + id);
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value
  getUser(id).then(response => {
    response.data.sex = String(response.data.sex);
    response.data.huaweiAuthorizeComplete = String(response.data.huaweiAuthorizeComplete);
    form.value = response.data;
    open.value = true;
    title.value = "修改用户";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["userForm"].validate(valid => {
    const avatar = form.value.avatar ? form.value.avatar[0]?.url || null : null
    if (valid) {
      if (form.value.id != null) {
        updateUser({
          ...form.value,
          avatar
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUser({
          ...form.value,
          avatar
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除数据项？').then(function () {
    return delUser(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('mobile/user/export', {
    ...queryParams.value
  }, `patient_${new Date().getTime()}.xlsx`)
}

function setDialogWidth() {
  var val = document.body.clientWidth
  console.log(val);
  const def = 500 // 默认宽度
  if (val < def) {
    dialogWidth.value = '100%'
  } else {
    dialogWidth.value = def + 'px'
  }
}

onMounted(() => {
  window.onresize = () => {
    return (() => {
      setDialogWidth()
    })()
  }
})

getList();
setDialogWidth();

</script>
